package approve.action;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import nguyen.dao.ReceiverDocumentDAO;

import project.active.LogoutActivity;

import memo.action.Memo_listview;
import model.pojo.Employee;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainList extends Activity{
	class PInfo {
		private String appname = "";
		private String pname = "";
		private String versionName = "";
		private int versionCode = 0;
	}

	static int soluong=0;
	TextView logout,username,welcome;
	String lang = "EN",database;
	Bundle language;
	Employee emp= new Employee();

	public String getDatabase() {
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			database = extras.getString("database");
		}
		return database;
	}

	Timer timer=new Timer();
	NotificationManager mNotificationManager=null;
	private int SIMPLE_NOTFICATION_ID;

	//auto update
	public int VersionCode;
	public String VersionName="";
	public String ApkName ;
	public String AppName ;
	public String BuildVersionPath="";
	public String urlpath ;
	public String PackageName;
	public String InstallAppPackageName;
	public String Text="";

	//
	private TextView txtEapproval;
	private TextView txtProvateMemo;
	private TextView txtProject;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		language = getIntent().getExtras().getBundle(getLang());


		if(LoginActivity.flagupdateversion==false){
			Text= "New".toString();
			ApkName = "EliERP.apk";//"Test1.apk";// //"DownLoadOnSDcard_01.apk"; //      
			AppName="Eli ERP";
			BuildVersionPath = "http://14.63.215.15/EliERP/approval_version.txt".toString();
			PackageName = "package:com.SelfInstall01".toString(); //"package:com.Test1".toString();
			urlpath = "http://14.63.215.15/EliERP/" + ApkName.toString();


			GetVersionFromServer(BuildVersionPath); 

			if(checkInstalledApp(AppName.toString()) == true)
			{   
				Toast.makeText(getApplicationContext(), language.getString("appfound")+" " + AppName.toString(), Toast.LENGTH_SHORT).show();
				System.out.println("login: true true");

			}else{
				Toast.makeText(getApplicationContext(),language.getString("appnotfound")+" "+ AppName.toString(), Toast.LENGTH_SHORT).show();          
				System.out.println("login: false false");
			}
			LoginActivity.flagupdateversion=true;
		}

		setContentView(R.layout.mainlist);

		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		emp=(Employee) getIntent().getExtras().get("em");
		showNotificationMessage();

		Intent currentIntent = this.getIntent();
		emp = (Employee)currentIntent.getSerializableExtra("em");

		//	    showDialogMessage();
		logout=(TextView)findViewById(R.id.logout);
		username=(TextView)findViewById(R.id.username);
		logout.setText(language.getString("Logout"));
		logout.setTextColor(Color.BLACK);
		
		welcome = (TextView)findViewById(R.id.welcome);
		welcome.setText(language.getString("ac_Welcome"));
		welcome.setTextColor(Color.BLACK);

		// 
		txtEapproval = (TextView)findViewById(R.id.id_eapproval);
		txtProvateMemo = (TextView)findViewById(R.id.id_privatememo);
		txtProject = (TextView)findViewById(R.id.id_project);

		txtEapproval.setText("E-Approval");
		txtProvateMemo.setText("Private Memo");
		txtProject.setText("Project");
		//
		logout.setOnClickListener(listenerLogout);
		username.setText(emp.getUserName());
		username.setTextColor(Color.parseColor("#013483"));

		// onclick textview
		txtEapproval.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainList.this, MainEApproval.class);

				intent.putExtra("lang", getLang());
				intent.putExtra("database", getDatabase());
				intent.putExtra("em",emp);
				intent.putExtras(getIntent().getExtras());

				startActivity(intent);
			}
		});

		txtProject.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainList.this, MainProject.class);

				intent.putExtra("lang", getLang());
				intent.putExtra("database", getDatabase());
				intent.putExtra("em",emp);
				intent.putExtras(getIntent().getExtras());

				startActivity(intent);
			}
		});
		
		txtProvateMemo.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainList.this, Memo_listview.class);

				intent.putExtra("lang", getLang());
				intent.putExtra("database", getDatabase());
				intent.putExtra("em",emp);
				intent.putExtras(getIntent().getExtras());

				startActivity(intent);
			}
		});
	}


	public String getLang() {
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			lang = extras.getString("lang");
		}
		return lang;
	}

	private OnClickListener listenerLogout=new OnClickListener() {

		public void onClick(View v) {
			LoginActivity.flagupdateversion=false;
			soluong=0;
			timer.cancel();
			mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);

			Intent i=new Intent(MainList.this, LogoutActivity.class);
			i.putExtra("database", getDatabase());
			startActivity(i);
		}
	};

	private void showNotificationMessage(){
		timer.scheduleAtFixedRate(new mainTask(), 500, 50000);
		//	
	}
	ReceiverDocumentDAO rd = new ReceiverDocumentDAO();
	private class mainTask extends TimerTask {

		@Override
		public void run() {
			mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
			final Notification notifyDetails;
			String idem = emp.getIdemployee();
			System.out.println("idem: "+idem);
			int count=rd.countAllNewMessage(idem, getDatabase());
			if(count>0){
				if(count!=soluong){
					soluong=count;
					notifyDetails = new Notification(R.drawable.ic_launcher,
							count + " new message", System.currentTimeMillis());

					notifyDetails.defaults = Notification.DEFAULT_ALL;
					Context context = getApplicationContext();
					CharSequence contentTitle = "You have " + count + " new message";
					CharSequence contentText = "click me to view detail";


					Intent notifyIntent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://14.63.219.99/checkAndroidToPC.jsp?dbname="+getDatabase()+"&user="+emp.getUserName()+"&lg="+getLang()));

					PendingIntent intent = PendingIntent.getActivity(MainList.this,
							0, notifyIntent,
							android.content.Intent.FLAG_ACTIVITY_NEW_TASK);

					notifyDetails.setLatestEventInfo(context, contentTitle,
							contentText, intent);
					mNotificationManager.notify(SIMPLE_NOTFICATION_ID,
							notifyDetails);

				}
			}

		}

	}

	private Boolean checkInstalledApp(String appName){
		return getPackages(appName);    
	}

	// Get Information about Only Specific application which is Install on Device.
	public String getInstallPackageVersionInfo(String appName) 
	{
		String InstallVersion = "";     
		ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
		final int max = apps.size();
		for (int i=0; i<max; i++) 
		{
			if(apps.get(i).appname.toString().equals(appName.toString()))
			{
				InstallVersion = apps.get(i).versionName.toString();
				break;
			}
		}
		Toast.makeText(getApplicationContext(),language.getString("currenversion")+" : " + InstallVersion.toString(), Toast.LENGTH_LONG).show();

		return InstallVersion.toString();
	}
	private Boolean getPackages(String appName) 
	{
		Boolean isInstalled = false;
		ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
		int max = apps.size();
		System.out.println(max);
		for (int i=0; i<max; i++) 
		{
			System.out.println(apps.get(i).appname.toString() + " - " + appName.toString());


			if(apps.get(i).appname.toString().equals(appName.toString()))
			{
				if(VersionCode <= apps.get(i).versionCode)
				{
					System.out.println("phien ban moi");
					isInstalled = false;

				}    
				if(VersionCode > apps.get(i).versionCode)
				{
					System.out.println("phien ban cu");
					isInstalled = true;

					DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() 
					{
						@Override
						public void onClick(DialogInterface dialog, int which) {
							switch (which)
							{
							case DialogInterface.BUTTON_POSITIVE:

								DownloadOnSDcard();
								InstallApplication();
								UnInstallApplication(PackageName.toString());

								break;

							case DialogInterface.BUTTON_NEGATIVE:
								//No button clicked

								break;
							}
						}
					};

					AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setMessage(language.getString("youareusingversion")+" "+getInstallPackageVersionInfo(AppName.toString()).toString()+". "+language.getString("nownewversion")
							+ GetVersionFromServer(VersionName.toString()).toString()+ ". "+language.getString("doyouwantinstall") +"?")
							.setPositiveButton(language.getString("install"), dialogClickListener)
							.setNegativeButton(language.getString("cancel"), dialogClickListener).show();              
				}
			}
		}




		return isInstalled;
	}
	private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) 
	{       
		ArrayList<PInfo> res = new ArrayList<PInfo>();        
		List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);

		for(int i=0;i<packs.size();i++) 
		{
			PackageInfo p = packs.get(i);
			if ((!getSysPackages) && (p.versionName == null)) {
				continue ;
			}
			if(p.applicationInfo.loadLabel(getPackageManager()).toString().equals(AppName)){
				PInfo newInfo = new PInfo();
				newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
				newInfo.pname = p.packageName;
				newInfo.versionName = p.versionName;
				newInfo.versionCode = p.versionCode;
				res.add(newInfo);
			}
		}
		return res; 
	}


	public void UnInstallApplication(String packageName)// Specific package Name Uninstall.
	{
		//Uri packageURI = Uri.parse("package:com.CheckInstallApp");
		Uri packageURI = Uri.parse(packageName.toString());
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		startActivity(uninstallIntent); 
	}
	public void InstallApplication()
	{   
		Uri packageURI = Uri.parse(PackageName.toString());
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW, packageURI);

		intent.setDataAndType
		(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/"  + ApkName.toString())), "application/vnd.android.package-archive");

		startActivity(intent);  
	}
	public String GetVersionFromServer(String BuildVersionPath)
	{
		//this is the file you want to download from the remote server          
		//path ="http://10.0.2.2:82/Version.txt";
		//this is the name of the local file you will create
		// version.txt contain Version Code = 2; \n Version name = 2.1;             
		URL u;
		try {
			u = new URL(BuildVersionPath.toString());

			HttpURLConnection c = (HttpURLConnection) u.openConnection();           
			c.setRequestMethod("GET");
			c.setDoOutput(true);
			c.connect();

			InputStream in = c.getInputStream();

			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			byte[] buffer = new byte[1024]; //that stops the reading after 1024 chars..

			int len1 = 0;
			while ( (len1 = in.read(buffer)) != -1 ) 
			{               
				baos.write(buffer,0, len1); // Write Into ByteArrayOutputStream Buffer.
			}

			String temp = "";     
			String s = baos.toString();// baos.toString(); contain Version Code = 2; \n Version name = 2.1;

			for (int i = 0; i < s.length(); i++)
			{               
				i = s.indexOf("=") + 1; 
				while (s.charAt(i) == ' ') // Skip Spaces
				{
					i++; // Move to Next.
				}
				while (s.charAt(i) != ';'&& (s.charAt(i) >= '0' && s.charAt(i) <= '9' || s.charAt(i) == '.'))
				{
					temp = temp.toString().concat(Character.toString(s.charAt(i))) ;
					i++;
				}
				//
				s = s.substring(i); // Move to Next to Process.!
				temp = temp + " "; // Separate w.r.t Space Version Code and Version Name.
			}
			String[] fields = temp.split(" ");// Make Array for Version Code and Version Name.

			VersionCode = Integer.parseInt(fields[0].toString());// .ToString() Return String Value.
			VersionName = fields[1].toString();

			System.out.println("Vesiom code _ " + VersionCode);
			System.out.println("Vesion name _ " + VersionName);
			baos.close();
		}
		catch (MalformedURLException e) {
			Toast.makeText(getApplicationContext(), "Error." + e.getMessage(), Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		} catch (IOException e) {           
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "Error." + e.getMessage(), Toast.LENGTH_SHORT).show();
		}
		return VersionName;
	}// Method End.

	// Download On My Mobile SDCard or Emulator.
	public void DownloadOnSDcard()
	{
		try{
			URL url = new URL(urlpath.toString()); // Your given URL.

			HttpURLConnection c = (HttpURLConnection) url.openConnection();
			c.setRequestMethod("GET");
			c.setDoOutput(true);
			c.connect(); // Connection Complete here.!

			String PATH = Environment.getExternalStorageDirectory() + "/download/";
			File file = new File(PATH); // PATH = /mnt/sdcard/download/
			if (!file.exists()) {
				file.mkdirs();
			}
			File outputFile = new File(file, ApkName.toString());           
			FileOutputStream fos = new FileOutputStream(outputFile);

			InputStream is = c.getInputStream(); // Get from Server and Catch In Input Stream Object.

			byte[] buffer = new byte[1024];
			int len1 = 0;
			while ((len1 = is.read(buffer)) != -1) {
				fos.write(buffer, 0, len1); // Write In FileOutputStream.
			}
			fos.close();
			is.close();
			System.out.println("thanh cong");
		} 
		catch (IOException e) 
		{
			System.out.println("that bai");
			System.out.println("Error! " +	e.toString());
			Toast.makeText(getApplicationContext(), "Error! " +	e.toString(), Toast.LENGTH_LONG).show();
		}           
	}
}
